package com.cs410.collabwriting.filters;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.cs410.collabwriting.tools.LogManager;

/**
 * Servlet Filter implementation class ProfanityFilter
 */
@WebFilter("*")
public class ProfanityFilter implements Filter {

    /**
     * Default constructor. 
     */
    public ProfanityFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * Web Service for profanity filter used from : http://api.inversoft.com:8001/content/handle.xml
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		Enumeration<String> param = request.getParameterNames();
		try {
		    while( param.hasMoreElements() ) {
		        String paramName = param.nextElement();
		        for (String value : request.getParameterValues(paramName) ) {		        
            		URL url = new URL("http://api.inversoft.com:8001/content/handle.xml");
            		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            		urlConnection.setDoInput(true);
            		urlConnection.setDoOutput(true);
            		urlConnection.setRequestMethod("POST");
            		urlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            		urlConnection.addRequestProperty("Authentication", "a79dd6524fb3b433b96359d138264933 ");
            		urlConnection.connect();
            
            		OutputStream out = urlConnection.getOutputStream();
            		OutputStreamWriter writer = new OutputStreamWriter(out);
            		writer.append("request.content=" + value).append(URLEncoder.encode("Some content to filter", "UTF-8")).append("&");
            		writer.append("request.filter.operation=locate").append("&");
            		writer.append("request.filter.enabled=true").append("&");
            		writer.append("request.filter.cleanspeakdb.enabled=true");
            		writer.flush();
            		writer.close();
            
            		InputStream inputStream = urlConnection.getInputStream();
            		Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
            		Element filter = (Element) dom.getDocumentElement().getElementsByTagName("filter").item(0);
            		NodeList matches = filter.getElementsByTagName("match");
            		if (matches.getLength() > 0) {
                        LogManager.logWarning("[ProfanityFilter][FOUND] -- " + ((Element) matches.item(0)).getAttribute("matched"));
                        JSONObject error = new JSONObject();
                        try {
                            error.put("error","true");
                            error.put("reason","Profanity is not tolerated here!");
                        } catch (JSONException e ) {}
                        
                        response.getWriter().print( error.toString() );
                        return;
            		}
            		inputStream.close();
		        }
		    }
		} catch (SAXException e1) {
			LogManager.logError( "[LogManager] -- " + e1.getMessage() );
		} catch (ParserConfigurationException e1) {
			LogManager.logError( "[LogManager] -- " + e1.getMessage() );
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
